package com.example.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.admin.entity.Configuration;
import com.example.admin.mapper.ConfigurationMapper;
import com.example.admin.model.dto.ConfigurationRequest;
import com.example.admin.service.ConfigurationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class ConfigurationServiceImpl implements ConfigurationService {

    @Autowired
    private ConfigurationMapper configurationMapper;

    @Override
    public IPage<Configuration> getConfigPage(ConfigurationRequest request) {
        LambdaQueryWrapper<Configuration> wrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (StringUtils.hasText(request.getType())) {
            wrapper.eq(Configuration::getType, request.getType());
        }
        if (StringUtils.hasText(request.getName())) {
            wrapper.like(Configuration::getName, request.getName());
        }
        if (StringUtils.hasText(request.getUserId())) {
            wrapper.eq(Configuration::getUserId, request.getUserId());
        }
        
        // 按创建时间降序排序
        wrapper.orderByDesc(Configuration::getCreateTime);
        
        return configurationMapper.selectPage(new Page<>(request.getCurrent(), request.getSize()), wrapper);
    }

    @Override
    public Configuration getById(Long id) {
        return configurationMapper.selectById(id);
    }

    @Override
    public Configuration getByTypeAndName(String type, String name, String userId) {
        LambdaQueryWrapper<Configuration> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Configuration::getType, type)
               .eq(Configuration::getName, name)
               .eq(Configuration::getUserId, userId);
        return configurationMapper.selectOne(wrapper);
    }

    @Override
    public void saveOrUpdate(Configuration configuration) {
        if (configuration.getId() == null) {
            configurationMapper.insert(configuration);
        } else {
            configurationMapper.updateById(configuration);
        }
    }

    @Override
    public void deleteById(Long id) {
        configurationMapper.deleteById(id);
    }
} 